//
//  LoginViewController.m
//  Contractor
//
//  Created by 金鑫 on 16/5/4.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "LoginViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "CodeWithDES.h"
#import "CustomTextField.h"
#import "MainTabBarViewController.h"
#import "ZhuceViewController.h"
#import "SetViewController.h"
#import "MBProgressHUD.h"
#import "CONST.h"
#import "DESEncryptFile.h"
#import "AppDelegate.h"
#import "LocationModel.h"

@interface LoginViewController ()<UITextFieldDelegate>
{
    UIScrollView *scrollView ;
    CustomTextField *account ;
    CustomTextField *password ;
    UIButton *loginBtn ;
    MBProgressHUD *hud ;
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES ;
    self.view.backgroundColor = [UIColor whiteColor] ;
    [self createBackView] ;
}

- (void)viewWillAppear:(BOOL)animated
{
    [hud hideAnimated:YES] ;
    //判断是否有账号密码
    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults] ;
    NSDictionary *loginInfoDic = [userD valueForKey:@"loginuserinfo"] ;
    if (loginInfoDic != NULL) {
        NSString *user = [loginInfoDic valueForKey:@"username"] ;
        NSString *passwd = [loginInfoDic valueForKey:@"password"] ;
        NSLog(@"user:%@,passwd:%@",user,passwd) ;
        account.text = user ;
        password.text = passwd ;
        NSLog(@"%@,%@",account.text,password.text) ;
    }

}

#pragma mark - 创建view
- (void)createBackView
{
    //标题栏
    UIImageView *titlebar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,__kScreenWidth, 60)] ;
    [titlebar setImage:[UIImage imageNamed:@"title_bg.png"]] ;
    
    UILabel *titleLabel = [[UILabel alloc] init] ;
    titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:24.0f] ;
    titleLabel.backgroundColor = [UIColor clearColor] ;
    titleLabel.text = @"包工婆" ;
    titleLabel.textColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:247/255.0 alpha:1] ;
    titleLabel.frame = CGRectMake(0, 25, __kScreenWidth, 26) ;
    titleLabel.textAlignment = NSTextAlignmentCenter ;
    [titlebar addSubview:titleLabel] ;
//    [self.view addSubview:titlebar] ;
    
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 60, __kScreenWidth, __kScreenHeight-60)] ;
    scrollView.backgroundColor = [UIColor whiteColor] ;
    scrollView.showsVerticalScrollIndicator = NO ;
    scrollView.bounces = NO ;
    [self.view addSubview:scrollView] ;
    
    //背景墙
    UIImageView *cover = [[UIImageView alloc] init] ;
    if (self.view.frame.size.height < 500) {
        cover.frame = CGRectMake(0, -22, __kScreenWidth, __kScreenWidth/2) ;
        [cover setContentScaleFactor:[[UIScreen mainScreen] scale]];
        cover.contentMode =  UIViewContentModeScaleAspectFill;
        //cover.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        cover.clipsToBounds  = YES;
    }
    else
    {
        cover.frame =  CGRectMake(0, -22, __kScreenWidth, __kScreenWidth*3/4) ;
        [cover setContentScaleFactor:[[UIScreen mainScreen] scale]];
        cover.contentMode =  UIViewContentModeScaleAspectFill;
        //cover.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        cover.clipsToBounds  = YES;
    }
    [cover setImage:[UIImage imageNamed:@"cover.jpg"]] ;
    [scrollView addSubview:cover] ;
    
    //账号输入框
    account = [[CustomTextField alloc] initWithFrame:CGRectMake(20, cover.frame.origin.y+cover.frame.size.height + 10, __kScreenWidth-40, 50)] ;
    [account setBackgroundColor:[UIColor clearColor]] ;
    account.placeholder = @"手机/用户名" ;
    account.delegate = self ;
    
    //账号最左侧图片
    UIImageView *leftImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)] ;
    [leftImage setImage:[UIImage imageNamed:@"login_username_icon.png"]] ;
    account.leftView = leftImage ;
    account.leftViewMode = UITextFieldViewModeAlways ;
    account.textAlignment = NSTextAlignmentLeft ;
    account.autocapitalizationType = UITextAutocapitalizationTypeNone ;//首字母不大写
    account.autocorrectionType = UITextAutocorrectionTypeNo ;//是否纠错
    [scrollView addSubview:account] ;
    
    //账号最右边图片
//    UIButton *rightImage2 = [[UIButton alloc] initWithFrame:CGRectMake(__kScreenWidth - 44, account.frame.origin.y + 13, 24, 24)] ;
    UIButton *rightImage2 = [[UIButton alloc] initWithFrame:CGRectMake(__kScreenWidth - 57, account.frame.origin.y, 50, 50)] ;
    [rightImage2 setImage:[UIImage imageNamed:@"login_del_username_normal_icon.png"] forState:UIControlStateNormal] ;
    [rightImage2 setImage:[UIImage imageNamed:@"login_del_username_press_icon.png"] forState:UIControlStateHighlighted] ;
    
    [rightImage2 setContentMode:UIViewContentModeCenter];
    [rightImage2 setImageEdgeInsets:UIEdgeInsetsMake(13, 13, 13, 13)];
    
    [rightImage2 addTarget:self action:@selector(cleartext) forControlEvents:UIControlEventTouchUpInside] ;
    [scrollView addSubview:rightImage2] ;
    
    //密码输入框
    password = [[CustomTextField alloc] initWithFrame:CGRectMake(20, account.frame.origin.y + account.frame.size.height + 10, __kScreenWidth-40, 50)] ;
    [password setBackgroundColor:[UIColor clearColor]] ;
    password.placeholder = @"密码" ;
    password.delegate = self ;
    
    //密码最左侧图片
    UIImageView *leftImage2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)] ;
    [leftImage2 setImage:[UIImage imageNamed:@"login_prassword_icon.png"]] ;
    password.leftView = leftImage2 ;
    password.leftViewMode = UITextFieldViewModeAlways ;
    password.textAlignment = NSTextAlignmentLeft ;
    password.autocapitalizationType = UITextAutocapitalizationTypeNone ;//首字母不大写
    password.autocorrectionType = UITextAutocorrectionTypeNo ;//是否纠错
    password.secureTextEntry = YES ;
    [scrollView addSubview:password] ;
    
    //密码最右边图片
//    UIButton *rightImage = [[UIButton alloc] initWithFrame:CGRectMake(__kScreenWidth - 44, password.frame.origin.y + 13, 24, 24)] ;
    UIButton *rightImage = [[UIButton alloc] initWithFrame:CGRectMake(__kScreenWidth - 57, password.frame.origin.y, 50, 50)] ;
    [rightImage setImage:[UIImage imageNamed:@"login_show_password_normal_icon.png"] forState:UIControlStateNormal] ;
    [rightImage setImage:[UIImage imageNamed:@"login_show_password_press_icon.png"] forState:UIControlStateHighlighted] ;
    
    [rightImage setContentMode:UIViewContentModeCenter];
    [rightImage setImageEdgeInsets:UIEdgeInsetsMake(13, 13, 13, 13)];
    
    [rightImage addTarget:self action:@selector(showpassword) forControlEvents:UIControlEventTouchUpInside] ;
    [scrollView addSubview:rightImage] ;
    
    //分割线
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(10, password.frame.origin.y-5, __kScreenWidth - 20, 1)] ;
    [line setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    [scrollView addSubview:line] ;
    UIImageView *line2 = [[UIImageView alloc] initWithFrame:CGRectMake(10, password.frame.origin.y + password.frame.size.height+5, __kScreenWidth - 20, 1)] ;
    [line2 setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    [scrollView addSubview:line2] ;
    [self.view addSubview:titlebar] ;
    
    loginBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    loginBtn.frame = CGRectMake(20, password.frame.origin.y + password.frame.size.height+70, __kScreenWidth - 40, 40) ;
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal] ;
    loginBtn.backgroundColor = [UIColor blueColor] ;
    loginBtn.layer.cornerRadius = 10.0f ;
    [loginBtn addTarget:self action:@selector(Login) forControlEvents:UIControlEventTouchUpInside] ;
    [scrollView addSubview:loginBtn] ;

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer
                                                     alloc] initWithTarget:self action:@selector(hideKeyBoard:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [scrollView addGestureRecognizer: tapGestureRecognizer];   //只需要点击非文字输入区域就会响应hideKeyBoard
    scrollView.contentSize = CGSizeMake(0, password.frame.origin.y + password.frame.size.height + 150) ;
    
//    //判断是否有账号密码
//    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults] ;
//    NSDictionary *loginInfoDic = [userD valueForKey:@"loginuserinfo"] ;
//    if (loginInfoDic != NULL) {
//        NSString *user = [loginInfoDic valueForKey:@"username"] ;
//        NSString *passwd = [loginInfoDic valueForKey:@"password"] ;
//        NSLog(@"user:%@,passwd:%@",user,passwd) ;
//        account.text = user ;
//        password.text = passwd ;
//        NSLog(@"%@,%@",account.text,password.text) ;
//    }

    //注册
    UILabel *zhuceLabel = [[UILabel alloc] init] ;
    zhuceLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
    zhuceLabel.backgroundColor = [UIColor clearColor] ;
    zhuceLabel.text = @"我要注册" ;
    zhuceLabel.textColor = [UIColor lightGrayColor] ;
    zhuceLabel.userInteractionEnabled = YES ;
    CGSize labelLength = [self lengthwithLabel:zhuceLabel withsize:16.0f] ;
    zhuceLabel.frame = CGRectMake(__kScreenWidth - labelLength.width - 20, password.frame.origin.y + password.frame.size.height + 20, labelLength.width, 18.0f) ;
    [scrollView addSubview:zhuceLabel] ;
    UIImageView *labelLine = [[UIImageView alloc] initWithFrame:CGRectMake(zhuceLabel.frame.origin.x, zhuceLabel.frame.origin.y+16, labelLength.width, 1)] ;
    [labelLine setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    [scrollView addSubview:labelLine] ;
    
    UITapGestureRecognizer *lableTap = [[UITapGestureRecognizer
                                                     alloc] initWithTarget:self action:@selector(zhuce)];

    [zhuceLabel addGestureRecognizer: lableTap];
    
}

- (CGSize)lengthwithLabel:(UILabel *)lable withsize:(CGFloat) size
{
    NSDictionary *attribute1 = @{NSFontAttributeName: [UIFont fontWithName:@"AvenirLTStd-Light" size:size]};
    CGSize DescSize = [lable.text boundingRectWithSize:CGSizeMake(MAXFLOAT, size) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
    return DescSize ;
}

#pragma mark - 注册
- (void)zhuce
{
    NSLog(@"注册") ;
    ZhuceViewController *vc = [[ZhuceViewController alloc] init] ;
    
    [self.navigationController pushViewController:vc animated:NO] ;
}

#pragma mark - 清除账户
- (void)cleartext
{
    account.text = nil ;
}
#pragma mark - 显示密码
- (void)showpassword
{
    password.secureTextEntry = !password.secureTextEntry ;
}
#pragma mark - 收起键盘
- (void)hideKeyBoard:(id)sender
{
    [account  resignFirstResponder] ;
    [password resignFirstResponder] ;
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0, 60, __kScreenWidth, __kScreenHeight-60);//上移60个单位，按实际情况设置
    scrollView.frame = rect;
    [UIView commitAnimations];
}

#pragma mark - textfieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder] ;
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0, 60, __kScreenWidth, __kScreenHeight-60);//上移60个单位，按实际情况设置
    scrollView.frame = rect;
    [UIView commitAnimations];
    
    return YES ;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:account]) {
        NSTimeInterval animationDuration=0.30f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        float width=scrollView.frame.size.width;
        float height=scrollView.frame.size.height;
        CGRect rect=CGRectMake(0.0f,-120+scrollView.contentOffset.y+__kScreenWidth/4,width,height);//上移80个单位，按实际情况设置
        if (self.view.frame.size.height < 500) {
            rect = CGRectMake(0.0f,-120+scrollView.contentOffset.y+__kScreenWidth/2,width,height);
        }
        scrollView.frame=rect;
        [UIView commitAnimations];
    }
    else{
    
        NSTimeInterval animationDuration=0.30f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        float width=scrollView.frame.size.width;
        float height=scrollView.frame.size.height;
        CGRect rect=CGRectMake(0.0f,-170+scrollView.contentOffset.y+__kScreenWidth/4,width,height+35);//上移80个单位，按实际情况设置
        if (self.view.frame.size.height < 500) {
            rect = CGRectMake(0.0f,-170+scrollView.contentOffset.y+__kScreenWidth/2,width,height);
        }
        scrollView.frame=rect;
        [UIView commitAnimations];
    }
    return YES ;
}

#pragma mark - 登录
- (void)Login
{
    
    
    NSLog(@"test") ;
    NSNumber *cmd = [[NSNumber alloc] initWithInt:2] ;
    NSNumber *type = [[NSNumber alloc] initWithInt:1] ;
    //NSDictionary *parameters = @{@"cmd":cmd};

    NSDictionary *jsondic = @{@"username": account.text,
                              @"password": password.text,
                              @"clienttype":type} ;
    NSLog(@"%@",jsondic) ;
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"登录jsonstr:%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd,@"jsonstr":jsonstr};
    NSLog(@"%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if ([jsondic[@"username"] isEqualToString:@""] ) {
        NSLog(@"username is  nil") ;
        loginBtn.enabled = NO ;
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 150)/2, password.frame.origin.y + password.frame.size.height+50, 150, 40)] ;
        [errorbtn setTitle:@"用户名不能为空!" forState:UIControlStateNormal] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        [scrollView addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
         NSLog(@"username:%@",jsondic[@"username"]) ;
    }
    else if ([jsondic[@"password"] isEqualToString:@""])
    {
        loginBtn.enabled = NO ;
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 150)/2, password.frame.origin.y + password.frame.size.height+50, 150, 40)] ;
        [errorbtn setTitle:@"密码不能为空!" forState:UIControlStateNormal] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        [scrollView addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else{
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = NSLocalizedString(@"登录中...", @"HUD loading title") ;
        [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            [hud hideAnimated:YES] ;
            
            //解密并解析json数据，将json转成字典
            NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
            
            decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
            NSLog(@"decodeStr:%@",decodeStr) ;
            NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
            id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
            if ([result isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dic = result ;
                NSLog(@"dic:%@",dic) ;
                if ([dic[@"status"]integerValue] == 1) {
                    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
                    [userDefault setValue:jsondic forKey:@"loginuserinfo"] ;
                    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
                    [uidDefaults setValue:dic[@"uid"] forKey:@"uid"] ;
                    
                    NSString *user = [[uidDefaults valueForKey:@"loginuserinfo"] valueForKey:@"username"] ;
                    NSString *passwd = [[uidDefaults valueForKey:@"loginuserinfo"] valueForKey:@"password"];
                    NSLog(@"user:%@,passwd:%@,uid:%@",user,passwd,[uidDefaults valueForKey:@"uid"]) ;
                    
                    /*
                     
                    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
                        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
                        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
                        NSLog(@"first launch第一次程序启动");

                        [self downLoadlocation] ;
                    }
                     */

//                    SetViewController *vc = [[SetViewController alloc] init] ;
//                    [self.navigationController pushViewController:vc animated:NO] ;
                    if ([dic[@"userset"] integerValue] == 1) {
                        NSLog(@"rootview is mainTabBar") ;
                        AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate] ;
                        MainTabBarViewController *vc = [[MainTabBarViewController alloc] init] ;
                        delegate.window.rootViewController = vc ;
                    }
                    else
                    {
                        SetViewController *vc = [[SetViewController alloc] init] ;
                        [self.navigationController pushViewController:vc animated:NO] ;
                    }
                }
                else
                {
                    UILabel *label = [[UILabel alloc] init] ;
                    label.font = [UIFont systemFontOfSize:14.0f] ;
                    label.text = dic[@"msg"] ;
                    label.textColor = [UIColor whiteColor] ;
                    label.textAlignment = NSTextAlignmentCenter ;
                    label.backgroundColor = [UIColor blackColor] ;
                    label.alpha = 0.8 ;
                    label.layer.cornerRadius = 10 ;
                    label.layer.masksToBounds = YES ;
                    label.frame = CGRectMake((__kScreenWidth - 150) / 2, password.frame.origin.y + password.frame.size.height+50, 150, 40) ;
                    label.numberOfLines = 0;
                    [scrollView addSubview:label] ;
                    [self performSelector:@selector(clearbtn:) withObject:label afterDelay:2.0] ;
                    
                }
            }
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            NSLog(@"%@",error) ;
            [hud hideAnimated:YES] ;
        }] ;

    }
}

- (void)clearbtn:(id)sender
{
    loginBtn.enabled = YES ;
    
    [sender removeFromSuperview] ;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
